import Image from 'next/image';
import { useState, useEffect } from 'react';
import { message } from 'antd';

const App = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const cardData = [
    {
      id: 1,
      avatar: '/images/avatar/1.jpg',
      nickname: '笋丁',
      tag: '圈主',
      content: '爱你是我做过最好的事',
      images: [
        '/images/avatar/1.jpg',
        '/images/avatar/2.jpg',
        '/images/avatar/3.jpg',
        '/images/avatar/4.jpg',
        '/images/avatar/5.jpg',
        '/images/avatar/6.jpg',
        '/images/avatar/7.jpg',
        '/images/avatar/8.jpg',
        '/images/avatar/9.jpg',
      ],
      publishTime: new Date('2024-03-20 10:00:00'),
      likes: ['森', '小妹妹', '原原'],
      comments: [
        { id: 1, user: '森', content: '评论爱你是我做过最好的事谢谢小妹妹们' },
        { id: 2, user: '森', content: '眼睛爱原原的 小妹妹好绝绝子' }
      ]
    },
    {
      id: 2,
      avatar: '/images/avatar/2.jpg',
      nickname: '小可爱',
      tag: '管理员',
      content: '今天天气真好，适合出去玩',
      images: [
        '/images/avatar/1.jpg',
        '/images/avatar/2.jpg',
        '/images/avatar/3.jpg',
        '/images/avatar/4.jpg',
        '/images/avatar/5.jpg',
        '/images/avatar/6.jpg',
        '/images/avatar/7.jpg',
        '/images/avatar/8.jpg'
      ],
      publishTime: new Date('2024-03-20 09:30:00'),
      likes: ['笋丁', '阳光', '微风'],
      comments: [
        { id: 1, user: '阳光', content: '确实是个好天气呢' }
      ]
    },
    {
      id: 3,
      avatar: '/images/avatar/3.jpg',
      nickname: '阳光',
      tag: '成员',
      content: '分享一些美食照片',
      images: [
        '/images/avatar/1.jpg',
        '/images/avatar/2.jpg',
        '/images/avatar/3.jpg',
        '/images/avatar/4.jpg',
        '/images/avatar/5.jpg',
        '/images/avatar/6.jpg',
        '/images/avatar/7.jpg'
      ],
      publishTime: new Date('2024-03-20 08:45:00'),
      likes: ['美食家', '小可爱'],
      comments: [
        { id: 1, user: '美食家', content: '看起来好美味啊' }
      ]
    },
    {
      id: 4,
      avatar: '/images/avatar/4.jpg',
      nickname: '微风',
      tag: '成员',
      content: '春天来了，花开正好',
      images: [
        '/images/avatar/1.jpg',
        '/images/avatar/2.jpg',
        '/images/avatar/3.jpg',
        '/images/avatar/4.jpg',
        '/images/avatar/5.jpg',
        '/images/avatar/6.jpg'
      ],
      publishTime: new Date('2024-03-19 20:15:00'),
      likes: ['花花', '草草', '树树'],
      comments: [
        { id: 1, user: '花花', content: '好美的春天' }
      ]
    },
    {
      id: 5,
      avatar: '/images/avatar/5.jpg',
      nickname: '星星',
      tag: '成员',
      content: '晚安，好梦',
      images: [
        '/images/avatar/1.jpg',
        '/images/avatar/2.jpg',
        '/images/avatar/3.jpg',
        '/images/avatar/4.jpg',
        '/images/avatar/5.jpg'
      ],
      publishTime: new Date('2024-03-19 22:00:00'),
      likes: ['月亮', '太阳'],
      comments: [
        { id: 1, user: '月亮', content: '晚安啦' }
      ]
    },
    {
      id: 6,
      avatar: '/images/avatar/6.jpg',
      nickname: '彩虹',
      tag: '成员',
      content: '雨后见彩虹',
      images: [
        '/images/avatar/1.jpg',
        '/images/avatar/2.jpg',
        '/images/avatar/3.jpg',
        '/images/avatar/4.jpg'
      ],
      publishTime: new Date('2024-03-19 16:30:00'),
      likes: ['雨滴', '云朵'],
      comments: [
        { id: 1, user: '雨滴', content: '太美了' }
      ]
    },
    {
      id: 7,
      avatar: '/images/avatar/7.jpg',
      nickname: '海浪',
      tag: '成员',
      content: '海边度假中',
      images: [
        '/images/avatar/1.jpg',
        '/images/avatar/2.jpg',
        '/images/avatar/3.jpg'
      ],
      publishTime: new Date('2024-03-19 14:20:00'),
      likes: ['沙滩', '椰子'],
      comments: [
        { id: 1, user: '沙滩', content: '好想去啊' }
      ]
    },
    {
      id: 8,
      avatar: '/images/avatar/8.jpg',
      nickname: '山峰',
      tag: '成员',
      content: '登山到顶峰',
      images: [
        '/images/avatar/1.jpg',
        '/images/avatar/2.jpg'
      ],
      publishTime: new Date('2024-03-19 11:00:00'),
      likes: ['云雾', '石头'],
      comments: [
        { id: 1, user: '云雾', content: '真厉害' }
      ]
    },
    {
      id: 9,
      avatar: '/images/avatar/9.jpg',
      nickname: '森林',
      tag: '成员',
      content: '森林里的小精灵',
      images: [
        '/images/avatar/1.jpg'
      ],
      publishTime: new Date('2024-03-19 09:15:00'),
      likes: ['树叶', '小鸟'],
      comments: [
        { id: 1, user: '小鸟', content: '好可爱呀' }
      ]
    },
    {
      id: 10,
      avatar: '/images/avatar/10.jpg',
      nickname: '月光',
      tag: '成员',
      content: '今晚月色真美',
      images: [
        '/images/avatar/1.jpg',
        '/images/avatar/2.jpg',
        '/images/avatar/3.jpg',
        '/images/avatar/4.jpg',
        '/images/avatar/5.jpg',
        '/images/avatar/6.jpg',
        '/images/avatar/7.jpg',
        '/images/avatar/8.jpg',
        '/images/avatar/9.jpg',
      ],
      publishTime: new Date('2024-03-19 20:00:00'),
      likes: ['星星', '夜空'],
      comments: [
        { id: 1, user: '星星', content: '确实很美' }
      ]
    }
  ];

  const [showModal, setShowModal] = useState(false);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [currentImages, setCurrentImages] = useState<string[]>([]);
  const [touchStart, setTouchStart] = useState(0);
  const [scale, setScale] = useState(1);
  const [lastScale, setLastScale] = useState(1);
  const [showPopup, setShowPopup] = useState<number | null>(null);

  const formatTime = (date: Date) => {
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const minutes = Math.floor(diff / (1000 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 5) return '刚刚';
    if (days === 1) return '昨天';
    if (days > 1) return `${days}天前`;
    return '今天';
  };

  const handleTouchStart = (e: React.TouchEvent) => {
    setTouchStart(e.touches[0].clientX);
  };

  // 处理缩放
  const handleTouchMove = (e: React.TouchEvent) => {
    if (e.touches.length === 2) {
      // 阻止默认行为以防止页面缩放
      e.preventDefault();
      
      // 计算两个触摸点之间的距离
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const currentDistance = Math.hypot(
        touch2.clientX - touch1.clientX,
        touch2.clientY - touch1.clientY
      );

      // 如果是第一次双指触摸，记录初始距离
      if (!lastScale) {
        setLastScale(currentDistance);
        return;
      }

      // 计算缩放比例
      let newScale = (scale * currentDistance) / lastScale;
      
      // 限制缩放范围
      newScale = Math.min(Math.max(1, newScale), 3);
      
      setScale(newScale);
      setLastScale(currentDistance);
    }
  };

  const handleTouchEnd = (e: React.TouchEvent) => {
    if (e.touches.length < 2) {
      setLastScale(1);
      
      // 如果是单指触摸结束，处理滑动
      const touchEnd = e.changedTouches[0].clientX;
      const diff = touchStart - touchEnd;
      
      // 只有在缩放比例为1时才允许滑动切换
      if (scale === 1 && Math.abs(diff) > 50) {
        if (diff > 0 && currentImageIndex < currentImages.length - 1) {
          setCurrentImageIndex(prev => prev + 1);
        } else if (diff < 0 && currentImageIndex > 0) {
          setCurrentImageIndex(prev => prev - 1);
        }
      }
    }
  };

  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    // 只有当缩放比例为1时，点击才会关闭预览
    if (scale === 1) {
      setShowModal(false);
    } else {
      // 如果已放大，点击时重置缩放
      setScale(1);
    }
  };

  const handleMoreClick = (e: React.MouseEvent, cardId: number) => {
    e.stopPropagation(); // 阻止事件冒泡
    setShowPopup(showPopup === cardId ? null : cardId);
  };

  useEffect(() => {
    const handleClickOutside = () => setShowPopup(null);
    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, []);

  return (
    <>
    {contextHolder}
    <div className="w-full">
      <div className="relative w-full h-[33.333vh]">
        <Image 
          src="/images/bg/me.jpg" 
          alt="顶部图片"
          fill
          className="object-cover"
          priority
        />
        <div className="absolute right-[5%] bottom-0 translate-y-1/3 flex items-start gap-3">
          <span className="text-white text-lg font-medium">笋丁</span>
          <Image
            src="/images/avatar/1.jpg"
            alt="头像"
            width={60}
            height={60}
            className="rounded-[6px] border-white"
          />
        </div>
      </div>

      {/* 添加内容卡片区域 */}
      <div className="max-w-2xl mx-auto mt-8 p-4">
        {cardData.map((card) => (
          <div key={card.id} className="flex gap-3 mb-8">
            {/* 左侧头像 */}
            <div className="w-[40px] h-[40px] flex-shrink-0">
              <Image
                src={card.avatar}
                alt="用户头像"
                width={40}
                height={40}
                className="rounded-[6px] object-cover"
              />
            </div>
            
            {/* 右侧内容区 */}
            <div className="flex-1">
              {/* 昵称 */}
              <h3 className="font-medium text-base">
                <span className="text-[#576b95]">{card.nickname}</span>
                <span className="text-[#B8860B] ml-1 text-sm">@{card.tag}</span>
              </h3>
              
              {/* 文字内容 */}
              <p className="mt-0 text-base text-black">{card.content}</p>
              
              {/* 图片内容 */}
              <div className="mt-2">
                {card.images.length === 1 ? (
                  <div 
                    onClick={() => {
                      setCurrentImageIndex(0);
                      setCurrentImages(card.images);
                      setShowModal(true);
                    }}
                    className="cursor-pointer"
                  >
                    <Image
                      src={card.images[0]}
                      alt="内容图片"
                      width={500}
                      height={300}
                      className="rounded-[4px] max-w-[80%] max-h-[50vh] object-contain"
                    />
                  </div>
                ) : (
                  <div className="grid grid-cols-3 gap-1 max-w-[500px]">
                    {card.images.map((image, index) => (
                      <div 
                        key={index} 
                        className="aspect-square relative cursor-pointer"
                        onClick={() => {
                          setCurrentImageIndex(index);
                          setCurrentImages(card.images);
                          setShowModal(true);
                        }}
                      >
                        <Image
                          src={image}
                          alt={`内容图片 ${index + 1}`}
                          fill
                          className="rounded-[4px] object-cover"
                        />
                      </div>
                    ))}
                  </div>
                )}
              </div>
              
              {/* 发布时间和操作按钮 */}
              <div className="mt-2 flex items-center justify-between relative">
                <span className="text-xs text-gray-400">{formatTime(card.publishTime)}</span>
                <div className="relative">
                  <button 
                    className="px-3 py-2 rounded-[2px] bg-[#f7f7f7]"
                    onClick={(e) => handleMoreClick(e, card.id)}
                  >
                    <div className="flex gap-[3px]">
                      <div className="w-[3px] h-[3px] rounded-full bg-[#576b95]"></div>
                      <div className="w-[3px] h-[3px] rounded-full bg-[#576b95]"></div>
                    </div>
                  </button>

                  {/* 弹出菜单 - 添加 Tailwind 动画类 */}
                  {showPopup === card.id && (
                    <div 
                      className="absolute right-full top-1/2 -translate-y-1/2 mr-2 bg-black/80 text-white rounded-[4px] z-10 
                      animate-[menuSlideIn_0.2s_ease-out]"
                    >
                      <div className="flex items-center whitespace-nowrap">
                        <div 
                          className="px-4 py-2 text-sm hover:bg-black/50 cursor-pointer flex items-center"
                          onClick={() => messageApi.warning('点赞功能开发中')}
                        >
                          <span className="mr-1">♡</span>
                          赞
                        </div>
                        <div className="w-[1px] h-4 bg-white/20"></div>
                        <div 
                          className="px-4 py-2 text-sm hover:bg-black/50 cursor-pointer flex items-center"
                          onClick={() => messageApi.warning('评论功能开发中')}
                        >
                          <span className="mr-1">💬</span>
                          评论
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* 评论区 */}
              <div className="mt-2.5 bg-[#f7f7f7] p-3 rounded-lg">
                {/* 喜欢 */}
                <div className="text-[#576b95] text-sm">
                  <span className="text-[#576b95] text-sm">♡</span>
                  <span className="ml-1">{card.likes.join('，')}</span>
                </div>
                
                {/* 分割线 */}
                <div className="my-2 border-b border-gray-200/80"></div>
                
                {/* 评论内容 */}
                {card.comments.map((comment) => (
                  <div key={comment.id} className="mt-2 first:mt-0">
                    <span className="font-medium text-[#576b95]">{comment.user}</span>
                    <span>：{comment.content}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 图片预览模态框 */}
      {showModal && (
        <div 
          className="fixed inset-0 bg-black z-50 flex items-center justify-center"
          onClick={() => scale === 1 && setShowModal(false)}
        >
          <div className="relative w-full h-full">
            {/* 图片 */}
            <div 
              className="w-full h-full flex items-center justify-center"
              onTouchStart={handleTouchStart}
              onTouchMove={handleTouchMove}
              onTouchEnd={handleTouchEnd}
            >
              <div 
                className="relative w-full h-full transition-transform"
                style={{ 
                  transform: `scale(${scale})`,
                  touchAction: 'none' // 防止浏览器默认的触摸行为
                }}
              >
                <Image
                  src={currentImages[currentImageIndex]}
                  alt={`预览图片 ${currentImageIndex + 1}`}
                  fill
                  className="object-contain"
                  onClick={handleClick}
                  draggable={false}
                />
              </div>
            </div>
            
            {/* 底部控制栏 - 只在未放大时显示 */}
            {currentImages.length > 1 && scale === 1 && (
              <div className="absolute bottom-10 left-1/2 -translate-x-1/2 flex items-center gap-4">
                {/* 左箭头 */}
                <button
                  className={`p-2 text-white/80 hover:text-white transition-opacity ${
                    currentImageIndex === 0 ? 'opacity-30 cursor-not-allowed' : 'cursor-pointer'
                  }`}
                  onClick={(e) => {
                    e.stopPropagation();
                    if (currentImageIndex > 0) {
                      setCurrentImageIndex(prev => prev - 1);
                    }
                  }}
                  disabled={currentImageIndex === 0}
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                  </svg>
                </button>

                {/* 计数器 */}
                <div className="text-white bg-black/50 px-4 py-1.5 rounded-full text-sm">
                  {currentImageIndex + 1} / {currentImages.length}
                </div>

                {/* 右箭头 */}
                <button
                  className={`p-2 text-white/80 hover:text-white transition-opacity ${
                    currentImageIndex === currentImages.length - 1 ? 'opacity-30 cursor-not-allowed' : 'cursor-pointer'
                  }`}
                  onClick={(e) => {
                    e.stopPropagation();
                    if (currentImageIndex < currentImages.length - 1) {
                      setCurrentImageIndex(prev => prev + 1);
                    }
                  }}
                  disabled={currentImageIndex === currentImages.length - 1}
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
    </>
  );
};

export default App;
